package com.xiaozheng.mybatis.SqlSession.proxy;

import com.xiaozheng.mybatis.cfg.Mapper;
import com.xiaozheng.mybatis.utils.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;

/**
 * @Package: com.xiaozheng.mybatis.SqlSession.proxy
 * @ClassName: MapperProxy
 * @Author: 小政同学    QQ:xiaozheng666888@qq.com
 * @CreateTime: 2020/8/28 13:19
 * @What_is_this_file_for: 这个文件是用来做什么的?
 * @Description: 描述
 */
public class MapperProxy implements InvocationHandler {
    //map的key是全限定类名+方法名
    private Map<String, Mapper> mappers;
    private Connection conn;

    public MapperProxy(Map<String,Mapper> mappers,Connection conn) {
        this.mappers = mappers;
        this.conn = conn;
    }
    /**
     * 代理方法，增强方法
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        //2.获取方法所在类的名称
        String className = method.getDeclaringClass().getName();
        //3组合key
        String key = className+"."+methodName;
        System.out.println("key = " + key);
        //4.获取mappers中的mapper对象
        Mapper mapper = mappers.get(key);
        //5.判断是否有mapper
        if (mapper == null) {
            //该方法执行，程序停止
            throw new IllegalArgumentException("传入参数异常");
        }
        //6.调用工具类执行查询所有
        return new Executor().selectList(mapper,conn);
    }
}
